package com.bwie.test;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.domain.User;
import com.bwie.exdomain.EsUser;
import com.bwie.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: lrz
 * @Date: 2024/10/24 19:44
 * @Description:
 **/
@Component
@Slf4j
public class SyncUser implements Job {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    UserMapper userMapper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("同步用户数据到ES的任务开始了");
        //检查并创建索引
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(EsUser.class);
        if(!indexOperations.exists()){
            //索引不存在就创建
            indexOperations.create();

            //创建映射
            Document mapping = indexOperations.createMapping();
            indexOperations.putMapping(mapping);
        }
        //查询数据库
        List<User> users = userMapper.selectList(null);
        
        //把数据库的对象转换为ES对象，然后存到ES中
        for (User user : users) {
            EsUser esUser = BeanUtil.toBean(user, EsUser.class);
            elasticsearchRestTemplate.save(esUser);
        }
        log.info("同步用户数据到ES的任务结束了");

    }
}
